package com.yzt.zhuju.utils;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;

import com.yzt.zhuju.config.AppConfig;
//import com.wildma.pictureselector.FileUtils;

import java.io.File;
import java.io.FileOutputStream;

/**
 * author : bob
 * date   : 2022/12/5
 * desc   :
 */
public class PictureUtils {

    public static final String APP_NAME = "PictureSelector";//app名称
    public static final String BASE_DIR = APP_NAME + File.separator;//PictureSelector/
    public static final String DIR_ROOT = "";//FileUtils.getRootPath() + File.separator + BASE_DIR;//文件夹根目录 /storage/emulated/0/PictureSelector/

    /**
     * 获取一个随机的存储图片的路径
     */
    public static String getImageSavePath() {
      //  FileUtils.createOrExistsDir(DIR_ROOT);
        return DIR_ROOT + APP_NAME + "_" + System.currentTimeMillis() + ".jpg";
    }

    /**
     * 获取存储图片的文件夹路径
     */
    public static String getImagePath() {
       // FileUtils.createOrExistsDir(DIR_ROOT);
        String pathName = DIR_ROOT;
        return pathName;
    }

    public static void saveBitmap(Bitmap bm, File file) {
        if (bm == null || file == null) {
            return;
        }
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            bm.compress(Bitmap.CompressFormat.JPEG, 80, fileOutputStream);
            fileOutputStream.flush();
            fileOutputStream.close();
        } catch (Exception e) {
            e.fillInStackTrace();
        }
    }

    public static void saveBitmap(Bitmap bm, OnSaveSuccessListener listener) {
        if (bm == null) {
            return;
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    File imageFile = new File(getImageSavePath());
                    String saveImagePath = imageFile.getAbsolutePath();
                    FileOutputStream fileOutputStream = new FileOutputStream(imageFile);
                    bm.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
                    fileOutputStream.flush();
                    fileOutputStream.close();
                    galleryAddPic(saveImagePath);
                    if (listener != null) {
                        listener.onSaveSuccess();
                    }
                } catch (Exception e) {
                    e.fillInStackTrace();
                }
            }
        }).start();
    }

    public interface OnSaveSuccessListener {

        void onSaveSuccess();
    }

    private static void galleryAddPic(String imagePath) {
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        File f = new File(imagePath);
        Uri contentUri = Uri.fromFile(f);
        mediaScanIntent.setData(contentUri);
        AppConfig.context.sendBroadcast(mediaScanIntent);
    }
}
